package com.h3bpm.kumhosunny.crm.controller.budget;

import OThinker.Common.DateTimeUtil;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataRow;
import data.DataTable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @authormi
 * @date2019/9/16
 */
@Controller
@RequestMapping("/Portal/CRM/BudgetReimbursement")
public class BudgetReimbursementController extends ControllerBase {


    @RequestMapping("/cancelAfterVerification")
    @ResponseBody
    public JSONObject  cancelAfterVerification(String instanceId){

         JSONObject result= new JSONObject();
         result.put("status",200);
         result.put("message","核销成功");
        try {
         SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         //取报销流程数据集合
         InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
         Map<String,Object>  reimbursement = instanceData.getBizObject().getValueTable();
            BizObject[]  reimbursementDetail= (BizObject[]) reimbursement.get("reimbursementDetail");
            for (BizObject obj : reimbursementDetail) {
                Map<String, Object> zbValueTable = obj.getValueTable();

                String selectEvectionInstanceIdSql = "select a.ObjectID from ot_instancecontext a where a.BizObjectId= '"+zbValueTable.get("travelObjId").toString()+"'";
                DataTable dataTable =  SqlUtil.doQuery(selectEvectionInstanceIdSql);
                String evectionInstanceId = dataTable.getEntityRows().get(0).getString("ObjectID");
                String getReimbursementMoney = "select appliedAmount,dateTravel,applicantId from k_budget_appropriation_schedule where  status = '4' and businessTravelRequestId= '"+evectionInstanceId+"'";
                DataTable  datatTable = SqlUtil.doQuery(getReimbursementMoney);



                //获取预算申请金额
                String  appliedAmount = datatTable.getEntityRows().get(0).getString("appliedAmount").toString();
                String   dateTravel =  datatTable.getEntityRows().get(0).getString("dateTravel").toString();
                String[] dateArray = dateTravel.split("-");
                String getDubgetSql = "select * from k_dubgetexpand where userId = '"+datatTable.getEntityRows().get(0).getString("applicantId").toString()+"' and byear='"+dateArray[0]+"' and  bmonth='"+dateArray[1]+"'";
                DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);


                //报销实际金额
                String amountReimbursement = zbValueTable.get("reimbursementMoney").toString();
                String objectId = UUID.randomUUID().toString();
                String insertBudgetDetailSql = "insert into k_budget_use_detail (objectId,amountReimbursement,status,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy,reimbursementInstanceId,budgetExpandId)" +
                        " values('"+objectId+"','"+amountReimbursement+"','"+2+"','"+simpleDateFormatUpdate.format(new Date())+"','"+instanceData.getBizObject().getCreatedBy()+"','"+simpleDateFormatUpdate.format(new Date())+"','"+instanceData.getBizObject().getCreatedBy()+"','"+instanceId+"','"+dataDubget.getEntityRows().get(0).getString("objectId")+"')";
                SqlUtil.doNoQuery(insertBudgetDetailSql);

                String budgetDetailExpandObjId = UUID.randomUUID().toString();
                String insertBudgetDetailExpand = "insert into  k_budget_use_detail_expand (objectId,budgetUseDetailId,evectionAppInstanceId,appMoney,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy)" +
                        " values('"+budgetDetailExpandObjId+"','"+objectId+"','"+evectionInstanceId+"','"+zbValueTable.get("planBudget").toString()+"','"+simpleDateFormatUpdate.format(new Date())+"','"+instanceData.getBizObject().getCreatedBy()+"','"+simpleDateFormatUpdate.format(new Date())+"','"+instanceData.getBizObject().getCreatedBy()+"')";
                SqlUtil.doNoQuery(insertBudgetDetailExpand);


                //获取锁定预算
                String lockBudget = dataDubget.getEntityRows().get(0).getString("lockBudget");
                //获取当前可用预算
                String availableBudget  = dataDubget.getEntityRows().get(0).getString("availableBudget");
                //可用预算加上出差申请金额
                BigDecimal availableBudgetMs = new BigDecimal(availableBudget).add(new BigDecimal(appliedAmount));
                //可用预算减去实际报销金额
                availableBudgetMs = availableBudgetMs.subtract(new BigDecimal(amountReimbursement));
                //释放预算锁定占用金额
                BigDecimal lockBudgetMs = new BigDecimal(lockBudget).subtract(new BigDecimal(appliedAmount));
                //预算拓展表释放
                String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+datatTable.getEntityRows().get(0).getString("applicantId").toString()+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , lockBudget ='"+lockBudgetMs+"' , availableBudget= '"+availableBudgetMs+"' where objectId ='"+dataDubget.getEntityRows().get(0).getString("objectId")+"'";
                SqlUtil.doNoQuery(updateDubgetSql);
                 //修改出差单核销状态
                String updateEvection = "update i_travelAppl set cancelAfterVerificationStatus ='2' where ObjectID = '"+zbValueTable.get("travelObjId").toString()+"'";
                SqlUtil.doNoQuery(updateEvection);
                BudgetSumSoloController.updatePracticalAvailableBudget(dateArray[0]+"-"+dateArray[1],datatTable.getEntityRows().get(0).getString("applicantId"));
            }

        } catch (Exception e) {
            result.put("status",500);
            result.put("message","系统异常");
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/getSubjectList")
    @ResponseBody
    public List<Map<String,String>> getSubjectList(){

        String getSql="select subjectCode,subjectName from i_subjectRelation ";

        try {
           List<Map<String,String>> list= new ArrayList<Map<String,String>>();
            DataTable dataTable = SqlUtil.doQuery(getSql);

            for(DataRow dataRow : dataTable.getEntityRows()){
                String subjectCode =    dataRow.getString("subjectCode");
                String subjectName =   dataRow.getString("subjectName");
                 Map<String,String> map = new HashMap<>(3);
                 map.put("subjectCode",subjectCode);
                 map.put("subjectName",subjectName);
                 list.add(map);
            }

          return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;

    }




    @RequestMapping("/getSystemProjectNumber")
    @ResponseBody
    public ResBody getSystemProjectNumber(){

        String returnProjectNumber = "";
        Date date = new Date();
        String dateStr = DateTimeUtil.getYear(date) + "" + String.format("%02d", DateTimeUtil.getMonth(date));
        String querySql = " SELECT reimbursementNum from I_claimsReimbursementProcess WHERE reimbursementNum LIKE '" + dateStr + "%' ORDER BY reimbursementNum DESC LIMIT 1 ";

        try {
            DataTable dataTable = SqlUtil.doQuery(querySql);

            if (dataTable.getRows() != null && dataTable.getRows().size() > 0) {
                String projectNumber = dataTable.getRows().get(0).getString(0);
                int num = Integer.valueOf(projectNumber.split(dateStr)[1]);
                returnProjectNumber = dateStr + String.format("%03d", num + 1);
            } else {
                returnProjectNumber = dateStr + "001";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResBody.buildSuccessResBody(returnProjectNumber);

    }




    @Override
    public String getFunctionCode() {
        return null;
    }
}
